﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Text;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Drawing2D;
using WControls.Drawable;

namespace WControls.Utils
{
    public static class CustomExtensions
    {
        public static SizeF MeasureDisplayStringSize(this Graphics graphics, string text, Font font)
        {
            StringFormat format = StringFormat.GenericTypographic;
            System.Drawing.RectangleF rect = new System.Drawing.RectangleF(0, 0,
                                                                          1000, 1000);
            System.Drawing.CharacterRange[] ranges = 
                                       { new System.Drawing.CharacterRange(0, 
                                                               text.Length) };
            System.Drawing.Region[] regions = new System.Drawing.Region[1];

            format.SetMeasurableCharacterRanges(ranges);

            regions = graphics.MeasureCharacterRanges(text, font, rect, format);
            rect = regions[0].GetBounds(graphics);

            format.Dispose();
            foreach (Region r in regions)
            {
                r.Dispose();
            }

            return new SizeF(rect.Right, rect.Bottom);
        }

        public static void AddRoundedRectangle(this GraphicsPath path, RectangleF rect, int cornerRadius)
        {
            if (cornerRadius > 0)
            {
                path.StartFigure();
                path.AddArc(rect.X, rect.Y, cornerRadius * 2, cornerRadius * 2, 180, 90);
                path.AddLine(rect.X + cornerRadius, rect.Y, rect.Right - cornerRadius * 2, rect.Y);
                path.AddArc(rect.X + rect.Width - cornerRadius * 2, rect.Y, cornerRadius * 2, cornerRadius * 2, 270, 90);
                path.AddLine(rect.Right, rect.Y + cornerRadius * 2, rect.Right, rect.Y + rect.Height - cornerRadius * 2);

                path.AddArc(rect.X + rect.Width - cornerRadius * 2, rect.Y + rect.Height - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 0, 90);

                path.AddLine(rect.Right - cornerRadius * 2, rect.Bottom, rect.X + cornerRadius * 2, rect.Bottom);
                path.AddArc(rect.X, rect.Bottom - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 90, 90);
                path.AddLine(rect.X, rect.Bottom - cornerRadius * 2, rect.X, rect.Y + cornerRadius * 2);
                path.CloseFigure();
            }
            else
            {
                path.AddRectangle(rect);
            }
        }

        public static bool IsFlagSet(this SegmentCorners me, SegmentCorners corners)
        {
            return (me & corners) == corners;
        }
    }
}
